<?php

namespace support;


use plugin\admin\app\model\Dict;

class Common
{
    public static function getAward($config)
    {
        $type = 0;
        if (isset($config['integral'])) {
            $type = Box::BOX_AWARD_TYPE_2;
        }
        if (isset($config['integral'])) {
            $type = Box::BOX_AWARD_TYPE_2;
        }
        if (isset($config['integral'])) {
            $type = Box::BOX_AWARD_TYPE_2;
        }
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param $startdate
     * @param $enddate
     * @return array
     */
    public static function getMonthDay()
    {
        $startdate = date("Y-m-01", time());
        $enddate = date("Y-m-d", strtotime("$startdate +1 month -1 day"));

        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;

        // 保存每天日期
        $date = array();

        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Ymd', $stimestamp + (86400 * $i));
        }

        return $date;
    }

    public static function getWeekDay()
    {
        $year = date('Y');   //获得年份, 例如： 2006
        $month = date('n');  //获得月份, 例如： 04
        $day = date('j');    //获得日期, 例如： 3
        $firstDay = date("w", mktime(0, 0, 0, $month, 1, $year));
        //获得当月第一天
        $daysInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
        //获得当月的总天数

        $tempDays = $firstDay + $daysInMonth;   //计算数组中的日历表格数
        $weeksInMonth = ceil($tempDays / 7);   //算出该月一共有几周（即表格的行数）
        //创建一个二维数组
        $counter = 0;
        for ($j = 0; $j < $weeksInMonth; $j++) {
            for ($i = 0; $i < 7; $i++) {
                $counter++;
                $week [$j] [$i] = $counter;
                //offset the days
                $week [$j] [$i] -= $firstDay;
                if (($week [$j] [$i] < 1) || ($week [$j] [$i] > $daysInMonth)) {
                    $week [$j] [$i] = "";
                }
            }
        }
        return $week;
    }

    public static function getWeekRelate($num)
    {
        $arr = [
            0 => '星期天',
            1 => '星期一',
            2 => '星期二',
            3 => '星期三',
            4 => '星期四',
            5 => '星期五',
            6 => '星期六',
        ];
        return $arr[$num] ?? '';
    }

    /**
     * 获取连续签到天数
     * @param $data
     * @return int
     */
    static function getKeepSignDay($data)
    {
        $data = array_column($data, 'day');
        rsort($data);

        $total = 0;
        $next = current($data);
        foreach ($data as $datum) {
            if ($datum == $next) {
                $next = $datum - 1;
                $total++;
            }
        }
        return $total;
    }

    //格式化时间
    public static function fmtDateTime($time)
    {
        return timestampToString($time);
    }

    //格式化分页数据
    public static function fmtPaginate($data)
    {
        if (empty($data)) {
            return [];
        }
        $list = [];
        foreach ($data as $datum) {
            $list[] = $datum ? $datum->toArray() : [];
        }
        return $list;
    }

    //格式化详情五图视频
    public static function fmtFile($data, $game_data = ''): array
    {
        if (empty($data)) {
            return [];
        }

        $list = [];
        $i = 1;
        foreach ($data as $key => $datum) {
            $file_type = Common::getFileType($datum);

            $banner_poster = '';
            if (Box::FILE_TYPE_2 == $file_type) {
                $banner_poster = $game_data['banner_poster'];
            }
            $list[] = [
                'id' => $i++,
                'file_type' => $file_type,
                'url' => getAbsoluteImageUrl($datum),
                'banner_poster' => getAbsoluteImageUrl($banner_poster),
            ];
        }
        return $list;
    }

    //格式化图片
    public static function fmtImages($images)
    {
        if (empty($images)) {
            return [];
        }
        $list = [];
        foreach ($images as $datum) {
            $list[] = getAbsoluteImageUrl($datum);
        }
        return $list;
    }

    //格式化小数
    public static function fmtFloat($val, $decimals = 2)
    {
        if (empty($val)) {
            return 0;
        }
        $val = number_format($val, $decimals, '.', '');
        return floatval(rtrim(rtrim($val, '0'), '.'));
    }

    /**
     * 返回本月开始和结束的时间戳
     *
     * @return array
     */
    public static function month()
    {
        return [
            mktime(0, 0, 0, date('m'), 1, date('Y')),
            mktime(23, 59, 59, date('m'), date('t'), date('Y'))
        ];
    }

    /**
     * 校验是否为合法手机号
     *
     * @param $phone
     *
     * @return false|int
     */
    public static function checkPhone($phone)
    {
        $_pattern = "/^1[23456789]\d{9}$/";

        return preg_match($_pattern, $phone);
    }

    /**
     * 校验是否为合法Email
     *
     * @param $email
     *
     * @return false|int
     */
    public static function checkEmail($email)
    {
        $_pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";

        return preg_match($_pattern, $email);
    }

    /**
     *判断姓名是否全是中文
     */
    static function isAllChinese($str)
    {
        //新疆等少数民族可能有·
        if (strpos($str, '·')) {
            //将·去掉，看看剩下的是不是都是中文
            $str = str_replace("·", '', $str);
            if (preg_match('/^[\x7f-\xff]+$/', $str)) {
                return true;//全是中文
            } else {
                return false;//不全是中文
            }
        } else {
            if (preg_match('/^[\x7f-\xff]+$/', $str)) {
                return true;//全是中文
            } else {
                return false;//不全是中文
            }
        }
    }

    /**
     * 消息类型-提示弹框
     * @param $str
     * @return bool
     */
    static function messageType1($content, $title = '提示')
    {
        $data['msg_type'] = 1;
        $data['title'] = $title;
        $data['content'] = $content;
        $data['button_content'] = "知道了";
        return $data;
    }

    /**
     * 消息类型-领取弹框
     * @param $str
     * @return bool
     */
    static function messageType2($title, $content, $sub_title = '获得的奖励')
    {
        if (empty($content)) {
            return [];
        }
        $data['msg_type'] = 2;
        $data['title'] = $title;
        $data['sub_title'] = $sub_title;
        $data['content'] = $content;
        $data['button_content'] = "领取";
        $data['request_api'] = "/api/v1/vip/draw";
        return $data;
    }

    /**
     * 消息类型-领取弹框
     * @param $str
     * @return bool
     */
    static function messageType3($title, $content)
    {
        if (empty($content)) {
            return [];
        }
        $data['msg_type'] = 3;
        $data['title'] = $title;
        $data['content'] = $content;
        $data['skip'] = 8;//6-我的平台币   7-我的积分 8-我的代金券
        return $data;
    }

    /**
     * 获取订单号
     * @return string
     */
    public static function getOrderId(): string
    {
        return date('YmdHis') . mt_rand(1000000, 9999999);
    }

    /**
     * 判断是否图片 1-图片  2-视频  3-其他
     * @param $url
     * @return int
     */
    public static function getFileType($url): int
    {
        if (preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $url)) {
            return Box::FILE_TYPE_1;
        }

        if (preg_match("/.*(\.avi|\.wmv|\.mpeg|\.mp4|\.m4v|\.mov|\.asf|\.flv|\.f4v|\.rmvb|\.rm|\.3gp|\.vob)$/", $url)) {
            return Box::FILE_TYPE_2;
        }
        return Box::FILE_TYPE_1;
    }

    /***
     * api返回{}
     * @return \ArrayObject
     */
    public static function emptyObject(): \ArrayObject
    {
        return new \ArrayObject();
    }

    public static function getTimeRange($start_time, $days): string
    {
        if (intval($start_time) !== $start_time) {
            $start_time = strtotime($start_time);
        }

        return timestampToString($start_time, 'Y.m.d') . '-' . timestampToString(strtotime("+{$days} days", $start_time), 'Y.m.d');
    }

    public static function getEndTime($start_time, $days)
    {
        $start_time = $start_time === intval($start_time) ? $start_time : strtotime($start_time);
        return strtotime("+{$days} days", $start_time);
    }

    /**
     * 获取默认用户头像
     * @return string
     */
    public static function getDefaultHeadImg(): string
    {
        return 'image/avatar/avatar_new.png';
    }

    /**
     * 格式化秒为指定格式
     * @param $time
     * @return int|string
     */
    public static function vTime($time)
    {
        $output = '';
        foreach (array(86400 => '天', 3600 => '小时', 60 => '分') as $key => $value) {
            if ($time >= $key) $output .= floor($time / $key) . $value;
            $time %= $key;
        }
        if ($output == '') {
            $output = 0;
        }
        return $output;
    }

    /**
     * 记录日志
     * @param $data
     * @param $file
     * @param $function
     * @param $line
     * @return void
     */
    public static function writeLog($data, $file = '', $function = '', $line = 0)
    {
        if (getenv("APP_DEBUG")) {
            $request = request();
            log::info(var_export($data, true), ['FILE' => $file, 'FUNCTION' => $function, "LINE" => $line, 'controller' => $request ? $request->controller : '', 'action' => $request ? $request->action : '']);
        }
    }

    /***
     * 纯文本换行
     * @param $str_content
     * @return array|string|string[]
     */
    public static function wrap($str_content)
    {
        return str_replace(["\r\n", "\n"], "<br/>", $str_content);
    }

    /**
     * 隐藏手机号中间四位
     * @param $str_content
     * @return array|string|string[]
     */
    public static function hidePhone($str_content)
    {
        if (self::checkPhone($str_content)) {
            return substr_replace($str_content, '****', 3, 4);
        }
        return $str_content;
    }

    public static function hideUserId($str_content)
    {
        return substr_replace($str_content, '***', 1, 3);
    }

    /*
     * 获取当月起止日期
     */
    public static function getCurrentMonth(): array
    {
        //获取本月开始的时间戳
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        //获取本月结束的时间戳
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        return [$beginThismonth, $endThismonth];
    }

    /*
    * 获取指定月份起止日期
    */
    public static function getMonth($month): array
    {
        $y = substr($month, 0, 4);
        $m = substr($month, 4);

        //获取本月开始的时间戳
        $beginThismonth = mktime(0, 0, 0, $m, 1, $y);
        //获取本月结束的时间戳
        $endThismonth = mktime(23, 59, 59, $m, date('t', $beginThismonth), $y);
        return [$beginThismonth, $endThismonth];
    }

    /**
     * php显示指定长度的字符串，超出长度以省略号(...)填补尾部显示
     * @ str 字符串
     * @ len 指定长度
     **/
    public static function cutSubstr($str, $len = 20)
    {
        if (mb_strlen($str) > $len) {
            $str = mb_substr($str, 0, $len) . '...';
        }
        return $str;
    }

    /**
     * @return void
     */
    public static function fmtPollNum($poll_num)
    {
        if ($poll_num > 10000) {
            return Common::fmtFloat($poll_num / 10000, 1) . "w";
        }
        return "{$poll_num}";
    }

    /**
     * 根据用户id生成邀请码
     * @param $userId
     * @return string
     */
    public static function getUserInviteCode($userId, $length = 7)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $num = strlen($chars);
        $str = '';
        while ($userId > 0) {
            $mod = $userId % $num;
            $userId = ($userId - $mod) / $num;
            $str = $chars[$mod] . $str;
        }

        // 不足用随机字符串补充，10表示邀请码邀请10位
        $str = str_pad($str, $length, self::createNonceStr($length - strlen($str)), STR_PAD_LEFT);
        return $str;
    }

    public static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 区间随机小数
     * @param $min
     * @param $max
     * @return float
     * @throws \Exception
     */
    public static function randFloat($min, $max)
    {
        if ($min >= $max) {
            return $min;
        }
        $rand = $min + mt_rand() / mt_getrandmax() * ($max - $min);
        return floatval(sprintf('%.2f', $rand));
    }

    /**
     * 判断是否中奖,支持10万分之一。
     * @param $ratio
     * @return bool
     */
    public static function isWin($ratio = 1)
    {
        $multi = 1;
        $rand_num = 0;
        if ($ratio >= 1) {
            $rand_num = rand(1, 100);
        } elseif ($ratio >= 0.1) {
            $rand_num = rand(1, 1000);
            $multi = 10;
        } elseif ($ratio >= 0.01) {
            $rand_num = rand(1, 10000);
            $multi = 100;
        } elseif ($ratio >= 0.001) {
            $rand_num = rand(1, 100000);
            $multi = 1000;
        }

        if ($rand_num && $rand_num <= $ratio * $multi) {
            return true;
        }
        return false;
    }

    /**
     * 判断是ios还是安卓
     * @return string
     */
    public static function getUserAgent($user_agent)
    {
        // 判断是否为iOS设备
        $is_ios = preg_match('/(iPhone|iPad|iPod)/', $user_agent);
        // 判断是否为安卓设备
        $is_android = preg_match('/Android/', $user_agent);
        if ($is_ios) {
            /*    echo "这是iOS手机";*/
            return 'ios';
        } elseif ($is_android) {
            /*echo "这是安卓手机";*/
            return 'android';
        } else {
            /*   echo "无法识别设备类型";*/
            return 'other';
        }
    }

    static function getDict($dict_key)
    {
        $dict_config = Dict::get($dict_key);
        $dic_conf = [];
        foreach ($dict_config as $item) {
            $dic_conf[$item['value']] = $item['name'];
        }
        return $dic_conf;
    }

}
